<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Business;
use app\common\model\Category;
use app\common\model\Goods as goodsModel;
use app\common\model\GoodsComment;
use app\common\model\User;
use think\Db;

/**
 * 产品接口
 */
class Goods extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 产品详情
     * @param string $goods_id 产品ID
     * @param string $token 用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1606196990",
    "data": {
    "id": 1,
    "category_id": 3,
    "business_id": 1,
    "name": "华为mate平板",产品名称
    "images": ["http:\/\/www.chanpin.com\/uploads\/20201123\/b612809cdaded818a367ec987d510786.png", "http:\/\/www.chanpin.com\/uploads\/20201124\/f89c6463af5980f89d3e9baae6a5dc19.jpg"],产品轮播图
    "price": "5800.00",产品价格
    "intro": "这是一个平板的简介。这是一个平板的简介。",产品简介
    "content": "<p style=\"text-align: center; \"><span style=\"background-color: rgb(255, 255, 0);\">经典华为平板<\/span><span style=\"background-color: rgb(255, 255, 0);\">经典华为平板<\/span><span style=\"background-color: rgb(255, 255, 0);\">经典华为平板<\/span><img src=\"http:\/\/www.chanpin.com\/uploads\/20201124\/ac5035a5688e83508c3a6722ffa76956.jpg\" ><\/p>",产品详情
    "createtime": 1606136084,
    "user_count": 0,当前用户是否收藏0否1是
    "comment_user": 1,评价人数
    "comment_count": 5,评价条数
    "comment_list": [{最新评价列表
    "id": 7,评价ID
    "content": "不错诶4",内容
    "username": "admin",用户名
    "avatar": "\/assets\/img\/avatar.png",头像
    "createtime": "11-23 20:54",时间
    "status_text": ""
    }, {
    "id": 6,
    "content": "不错诶3",
    "username": "admin",
    "avatar": "\/assets\/img\/avatar.png",
    "status_text": ""
    }]
    }
    })
     */
    public function detail()
    {
        $goods_id  = $this->request->get('goods_id');
        $token  = $this->request->get('token');
        $user = User::where('token',$token)->field('id')->find();
        $goods_info = goodsModel::where('id',$goods_id)->find();
        if($goods_info){
            $images = explode(',',$goods_info['images']);
            foreach($images as &$v){
                $v = $this->domain.$v;
            }
            $goods_info['images'] = $images;
            //$info['content'] = get_img_thumb_url($goods_info['content'],$this->domain);
            $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
            $goods_info['content'] = preg_replace($pregRule, '<img src="' . $this->domain . '${1}" >', $goods_info['content']);
            //当前用户是否收藏
            $goods_info['user_count'] = Db::name('user_collect')->where(['userid'=>$user['id'],'goods_id'=>$goods_info['id']])->count();
            //评价人数
            $goods_info['comment_user'] = GoodsComment::where('goods_id',$goods_info['id'])->group('userid')->count();
            //评价条数
            $goods_info['comment_count'] = GoodsComment::where('goods_id',$goods_info['id'])->count();
            //最新两条评论
            $comment_list = GoodsComment::alias('c')->join('user u','u.id = c.userid')->where('c.to_contentid',0)->field('c.id,c.content,u.username,u.avatar,c.createtime')->order('c.id desc')->limit(2)->select();
            foreach($comment_list as &$value){
                $value['createtime'] = date('m-d H:i',$value['createtime']);
            }
            $goods_info['comment_list'] = $comment_list;
            $this->success($goods_info);
        }
        $this->error('产品不存在');
    }
    /**
     * 更多评论
     * @param string $goods_id 产品ID
     * @param string $token 用户token
     * @param string $page 页数（默认为1）
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1606198692",
    "data": [
    {
    "id": 6,评论ID
    "username": "admin",用户名
    "avatar": "/assets/img/avatar.png",头像
    "content": "不错诶3",评论
    "createtime": "11-23 20:54",时间
    "child_comment": [],二级评论列表
    "status_text": ""
    },
    {
    "id": 3,
    "username": "admin",
    "avatar": "/assets/img/avatar.png",
    "content": "不错诶",
    "createtime": "11-23 20:54",
    "child_comment": [
    {
    "username": "admin",用户名
    "avatar": "/assets/img/avatar.png",头像
    "content": "不错诶3",评论
    "createtime": "11-23 20:54",时间
    "status_text": ""
    },
    {
    "username": "admin",
    "avatar": "/assets/img/avatar.png",
    "content": "哎哟",
    "createtime": "11-24 14:13",
    "status_text": ""
    }
    ],
    "status_text": ""
    }
    ]
    })
     */
    public function comment_more()
    {
        $goods_id  = $this->request->get('goods_id');
        $token  = $this->request->get('token');
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $pagesize = 10;
        $page = ($page-1)*$pagesize;
        $goods_info = goodsModel::where('id',$goods_id)->find();
        if($goods_info){
            $first_comment =GoodsComment::alias('c')->join('user u','u.id = c.userid')->where(['c.goods_id'=>$goods_info['id'],'c.to_contentid'=>0])->field('c.id,u.username,u.avatar,c.content,c.createtime')->limit($page,$pagesize)->order('c.createtime desc')->select();
            foreach($first_comment as &$value){
                $value['createtime'] = date('m-d H:i',$value['createtime']);
                $arr = GoodsComment::alias('c')->join('user u','u.id = c.userid')->where(['c.to_contentid'=>$value['id']])->field('u.username,u.avatar,c.content,c.createtime')->order('c.createtime desc')->select();
                foreach($arr as  &$v1){
                    $v1['createtime'] = date('m-d H:i',$v1['createtime']);
                }
                $value['child_comment'] = $arr;
            }
            $this->success($first_comment);
        }
        $this->error('产品不存在');
    }
    /**
     * 收藏产品
     * @ApiMethod   (POST)
     * @param string $goods_id 商品ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function collect()
    {
        $token = $this->request->post('token');
        $goods_id = $this->request->post('goods_id');
        $user = User::where('token',$token)->field('id')->find();
        $goods_info = goodsModel::where('id',$goods_id)->count();
        if($goods_info == 0){
            $this->error('产品不存在');
        }
        $collect_count = Db::name('user_collect')->where(['userid'=>$user['id'],'goods_id'=>$goods_id])->count();
        if($collect_count){
            $this->error('您已经收藏过了');
        }
        $data = [
            'userid'=>$user['id'],
            'goods_id'=>$goods_id,
            'createtime'=>time(),
        ];
        Db::startTrans();
        try {
            $res = Db::name('user_collect')->insert($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','收藏成功');
        }
        $this->error('收藏失败');
    }
    /**
     * 取消收藏产品
     * @ApiMethod   (POST)
     * @param string $goods_id 商品ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function cancel_collect()
    {
        $token = $this->request->post('token');
        $goods_id = $this->request->post('goods_id');
        $user = User::where('token',$token)->field('id')->find();
        $goods_info = goodsModel::where('id',$goods_id)->count();
        if($goods_info == 0){
            $this->error('产品不存在');
        }
        $collect_count = Db::name('user_collect')->where(['userid'=>$user['id'],'goods_id'=>$goods_id])->count();
        if($collect_count == 0){
            $this->error('您没有收藏该产品');
        }
        Db::startTrans();
        try {
            $res = Db::name('user_collect')->where(['userid'=>$user['id'],'goods_id'=>$goods_id])->delete();
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','取消收藏成功');
        }
        $this->error('取消失败');
    }
    /**
     * 评论
     * @ApiMethod   (POST)
     * @param string $goods_id   产品ID
     * @param string $to_contentid      评论ID，第一条为0
     * @param string $token      用户token
     * @param string $content      内容
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function comment_submit()
    {
        $token = $this->request->post('token');
        $to_contentid = $this->request->post('to_contentid');
        $goods_id = $this->request->post('goods_id');
        $content = $this->request->post('content');
        $user = User::where('token',$token)->field('id')->find();
        $info = goodsModel::where(['id'=>$goods_id])->count();
        if($info){
            $count = GoodsComment::where('id',$to_contentid)->count();
            if($count == 0){
                $to_contentid = 0;
            }
            Db::startTrans();
            try {
                $res = GoodsComment::insert(['goods_id'=>$goods_id,'userid'=>$user['id'],'to_contentid'=>$to_contentid,'content'=>$content,'createtime'=>time()]);
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('','评论成功');
            }else{
                $this->error('评论失败');
            }
        }else{
            $this->error('数据异常');
        }
    }
}
